<?php
/**
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */

namespace app\mobile\controller;

use AlibabaCloud\SDK\ICE\V20201109\ICE;
use AlibabaCloud\SDK\ICE\V20201109\Models\GetSmartHandleJobRequest;
use AlibabaCloud\SDK\ICE\V20201109\Models\SubmitASRJobRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use app\admin\model\FigureAiTitle;
use app\admin\model\Homepage;
use app\admin\model\HomepageVideo;
use app\BaseController;
use app\common\service\AgentApiService;
use app\common\service\ApiService;
use OSS\OssClient;
use think\App;
use think\facade\Request;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use app\admin\model\FigureUser;
use app\admin\model\FigureAicreate;
use app\common\service\AIService;

/**
 * AI创作操作
 *
 * @author Administrator
 *
 */
class AiCreate extends BaseController
{


    public function accountInfo()
    {
        $uid = input('uid');
        $type = input('type');
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }

        if (!$user['is_member']) {
            if ($type == 2) {
                $tally = sysconfig('tally', 'ai_video_extraction');
            } elseif ($type == 1) {
                $tally = sysconfig('tally', 'ai_create_deduct');
            } elseif ($type == 3) {
                $tally = sysconfig('tally', 'ai_title_create_deduct');
            }
            if ($user['balance'] < $tally) {
                return result(-2, '余额不足，请充值');
            }
            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();
            } else {
                $apiService = new ApiService();
            }

            $result = $apiService->info();
            if ($result['data']['balance'] < $tally) {
                return result(-1, '平台点数不足请联系管理员');
            }
        }
        return result(0, 'success');

    }

    /**
     * test
     * http://aigc.weijuyunke.cn/mobile/aiCreate/test
     */
    public function test()
    {
        try {
            $aiService = new AIService();
            $result = $aiService->xfyun("企业名称 微聚云科; 生成产品: 数字人；企业实力:专注数字人开发100年；推广目的：招商引流");

            if (isset($result['code']) && $result['code'] == 1) {
                return result(0, '生成成功', $result['data']);
            } else {
                return result(-1, $result['msg']);
            }
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 分类类型
     * http://aigc.weijuyunke.cn/mobile/aiCreate/typeList
     */
    public function typeList()
    {
        try {

            $domain = $this->request->domain();

            $defaults = [
                /*  array(
                      'type' => 1,
                      'name' => "生产工厂",
                      'icon' => $domain . "/imgs/bottom/indexa.png",
                      'desc' => "专为生产型企业、厂家提供短视频文案AI代写",
                  ),
                  array(
                      'type' => 2,
                      'name' => '团购商家',
                      'icon' => $domain . "/imgs/bottom/info.png",
                      'desc' => "专为本地生活服务团购套餐提供AI文案代写",
                      'status' => 0,
                  ),
                  array(
                      'type' => 3,
                      'name' => '零售商家',
                      'icon' => $domain . "/imgs/bottom/shop.png",
                      'desc' => "专为各类零售商家提供短视频AI文案代写",

                  ),
                  array(
                      'type' => 4,
                      'name' => '智能代写',
                      'icon' => $domain . "/imgs/bottom/third.png",
                      'desc' => "用AI根据你输入的想法要求自由一键代写各类文案",

                  ),
                  array(
                      'type' => 5,
                      'name' => '文案仿写',
                      'icon' => $domain . "/imgs/bottom/user.png",
                      'desc' => "根据你提供的文案通过AI自动仿照多个类似文案",
                  )*/
                array(
                    'type' => 6,
                    'name' => "企业宣传",
                    'icon' => $domain . "/imgs/bottom/propaganda.png",
                    'desc' => "企业宣传",
                ),

                array(
                    'type' => 7,
                    'name' => "同城团购",
                    'icon' => $domain . "/imgs/bottom/e-commerce_sales.png",
                    'desc' => "团购产品文案",
                ),
                array(
                    'type' => 8,
                    'name' => "电商带货",
                    'icon' => $domain . "/imgs/bottom/same_city_group.png",
                    'desc' => "带货营销文案",
                ),
                array(
                    'type' => 9,
                    'name' => "知识科普",
                    'icon' => $domain . "/imgs/bottom/Knowledge_popularization.png",
                    'desc' => "知识获取很方便",
                ),
                array(
                    'type' => 10,
                    'name' => "情感专家",
                    'icon' => $domain . "/imgs/bottom/Emotional_expert.png",
                    'desc' => "情感问题一点通",
                ),
                array(
                    'type' => 11,
                    'name' => "口播文案",
                    'icon' => $domain . "/imgs/bottom/oral_broadcasting_article.png",
                    'desc' => "播音必备神器",
                ),
                array(
                    'type' => 12,
                    'name' => "朋友圈营销",
                    'icon' => $domain . "/imgs/bottom/friendvertising.png",
                    'desc' => "轻松搞定营销文案",
                ),
                array(
                    'type' => 13,
                    'name' => "小红书笔记",
                    'icon' => $domain . "/imgs/bottom/xiaohongshunotes.png",
                    'desc' => "小红书笔记",
                ),
                array(
                    'type' => 14,
                    'name' => '文案仿写',
                    'icon' => $domain . "/imgs/bottom/copy_imitation.png",
                    'desc' => "根据你提供的文案通过AI自动仿照多个类似文案",
                ),
                array(
                    'type' => 15,
                    'name' => '智能代写',
                    'icon' => $domain . "/imgs/bottom/intelligent_ghostwriting.png",
                    'desc' => "根据你提供的文案通过AI自动仿照多个类似文案",
                ),
                array(
                    'type' => 18,
                    'name' => 'deekseep文案',
                    'icon' => $domain . "/imgs/bottom/intelligent_ghostwriting.png",
                    'desc' => "根据你提供的文案通过AI自动仿照多个类似文案",
                ),
                array(
                    'type' => 19,
                    'name' => 'ai标题',
                    'icon' => $domain . "/imgs/bottom/intelligent_ghostwriting.png",
                    'desc' => "根据你提供的文案通过AI自动仿照多个类似文案",
                ),

            ];

            return result(0, 'success', $defaults);
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * AI创作
     * http://aigc.weijuyunke.cn/mobile/aiCreate/add
     *
     * @param
     *            uid 用户id
     * @param
     *            name 任务名称
     * @param
     *            type 1-生产工厂 2-团购商家 3-零售商家 4-智能代写 5-文案仿写
     * @param
     *            store_name 商家名称
     * @param
     *            product 产品
     * @param
     *            price 价格
     * @param
     *            desc 介绍
     * @param
     *            guide 引导目的
     * @param
     *            words 文案字数
     * @param
     *            rows 生成条数
     */
    public function add()
    {
        try {
            $uid = input('uid');
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }
            $data = array(
                'uid' => $uid,
                'name' => input('name'),
                'type' => input('type'),
                'rows' => 1,
                'question' => input('question'),
                'answer' => input('answer'),
                'status' => 2
            );
            // 'words' => input('words'),
            if (input('words') == 1) {
                $data['words'] = 150;
            } else if (input('words') == 2) {
                $data['words'] = 250;
            } else {
                $data['words'] = 500;
            }
            if ($data['type'] == 16) {
                $tally = sysconfig('tally', 'ai_video_extraction');
            } else {
                $tally = sysconfig('tally', 'ai_create_deduct');
            }
            if (!$user['is_member']) {
                if ($user['balance'] < $tally) {
                    return result(-2, '余额不足，请充值');
                }
            } else {
                if ($user['ai_copywriting_times'] < 1 && $user['balance'] < $tally) {
                    return result(-2, '余额不足，请充值');
                }
            }


            if (sysconfig('account', 'operation_version') == 2) {
                $apiService = new AgentApiService();

            } else {
                $apiService = new ApiService();

            }
            $result = $apiService->aiCreatePoints($data['type']);
            if ($result['code'] == 1) {
                $log_no = getPayNo('AI');
                if ($data['type'] == 16) {
                    user_balance_used($uid, $log_no, 2, 12, $data['rows']);
                } else {
                    user_balance_used($uid, $log_no, 2, 8, $data['rows']);
                }

            } else {
                return result(-1, '生成失败');
            }

            $create = new FigureAicreate();
            $create->save($data);
            return result(0, '生成成功');


        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 创作记录
     * http://aigc.weijuyunke.cn/mobile/aiCreate/createList
     *
     * @param
     *            uid 用户id
     * @param
     *            name 名称
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function createList()
    {
        try {
            $uid = input('uid');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }
            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));
            $where = " uid = {$uid} ";
            if (!empty(input('name'))) {
                $name = input('name');
                $where .= " AND name LIKE '%{$name}%'";
            }
            if (!empty(input('type'))) {
                $type = input('type');
                if ($type == 20) {
                    $where .= " AND (type =20 or  type = 16) ";
                }

            } else {
                $where .= " AND (type <> 20 and  type <> 16) ";
            }
            if (!empty(input('is_status'))) {
                $is_status = input('is_status');
                $where .= " AND is_status = '{$is_status}'";
            }
            $total = FigureAicreate::where($where)->count();
            if ($total) {
                $list = FigureAicreate::where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
            } else {
                $list = array();
            }
            $totalPage = ceil($total / $psize);
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    function generate($data)
    {
        $question = "";

        if ($data['type'] == 1) { // 生产工厂
            $question = "企业名称：{$data['store_name']}；生成产品：{$data['product']}；企业实力：{$data['desc']}；推广目的：{$data['guide']}；生成条数：{$data['rows']}";
        } elseif ($data['type'] == 2) { // 团购商家
            $question = "商家名称：{$data['store_name']}；团购套餐价格：{$data['price']}；套餐介绍：{$data['desc']}；引导下单：{$data['guide']}；生成条数：{$data['rows']}";
        } elseif ($data['type'] == 3) { // 零售商家
            $question = "商家名称：{$data['store_name']}；商品价格：{$data['price']}；商品介绍：{$data['desc']}；引导下单：{$data['guide']}；生成条数：{$data['rows']}";
        } elseif ($data['type'] == 4) { // 智能代写
            $question = "智能代写：{$data['desc']}；生成条数：{$data['rows']}";
        } elseif ($data['type'] == 5) {  // 文案仿写
            $question = "文案仿写：{$data['desc']}；生成条数：{$data['rows']}";
        } elseif ($data['type'] == 6) {  // 企业宣传
            $question = "公司名称：{$data['corporate_name']};公司简称:{$data['company_abbreviation']};主营业务:{$data['main_business']};公司特色:{$data['company_features']};生成：{$data['words']}字以内";
        } elseif ($data['type'] == 7) {  // 同城团购
            $question = "店铺名称：{$data['shop_name']};团购套餐:{$data['group_buying_package']}";
            if (isset($data['original_price']) && !empty($data['original_price'])) {
                $question .= "套餐原价：{$data['original_price']};";
            }
            if (isset($data['group_buying_price']) && !empty($data['group_buying_price'])) {
                $question .= "套餐原价：{$data['group_buying_price']};";
            }
            $question .= "引导下单词：{$data['guide']};";
            $question .= "生成：{$data['words']}字以内";
        } elseif ($data['type'] == 8) { //电商带货
            $question = "商品名称：{$data['product_name']};商品特色:{$data['product_features']};优惠价格:{$data['preferential_price']};引导下单词：{$data['guide']};生成：{$data['words']}字以内";
        } elseif ($data['type'] == 9) { //知识科普
            $question = "科普主题：{$data['science_popularization_theme']};内容补充:{$data['science_popularization_content']};生成：{$data['words']}字以内";
        } elseif ($data['type'] == 10) { //知识科普
            $question = "科普主题：{$data['science_popularization_theme']};内容补充:{$data['science_popularization_content']};生成：{$data['words']}字以内";
        }


        return $question;
    }

    /**
     * 创作详情
     * http://aigc.weijuyunke.cn/mobile/aiCreate/createDetail
     *
     * @param
     *            uid 用户id
     * @param
     *            create_id 创作id
     */
    public function createDetail()
    {
        try {
            $uid = input('uid');
            $create_id = input('create_id');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $create = FigureAicreate::where([
                'uid' => $uid,
                'id' => $create_id
            ])->find();
            if (empty($create)) {
                return result(-1, '创作不存在');
            }

            return result(0, 'success', $create);
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 创作删除
     * http://aigc.weijuyunke.cn/mobile/aiCreate/createDel
     *
     * @param
     *            uid 用户id
     * @param
     *            create_id 创作id
     */
    public function createDel()
    {
        try {
            $uid = input('uid');
            $create_id = input('create_id');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $create = FigureAicreate::where([
                'uid' => $uid,
                'id' => $create_id
            ])->find();
            if (empty($create)) {
                return result(-1, '创作不存在');
            }

            $create->delete();
            return result(0, '删除成功');
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 创作删除
     * http://aigc.weijuyunke.cn/mobile/aiCreate/createDel
     *
     * @param
     *            uid 用户id
     * @param
     *            create_id 创作id
     */
    public function edit()
    {
        $request = $this->request;
        $param = $request->param();
        $data = array(
            'answer' => input('answer'),

        );
        $create = new FigureAicreate();
        $create->where(['id' => $param['id']])->update($data);
        return result(0, '修改成功');
    }

    public function addTitle()
    {
        $uid = input('uid');
        $request = $this->request;
        $param = $request->param();
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }
        $tally = sysconfig('tally', 'ai_title_create_deduct');
        $money = count($param['answer']) * $tally;
        if (!$user['is_member']) {
            if ($user['balance'] < $money) {
                return result(-2, '余额不足，请充值');
            }
        } else {
            if ($user['ai_title_times'] < count($param['answer']) && $user['balance'] < $money) {
                return result(-2, '余额不足，请充值');
            }
        }
        $data = array(
            'uid' => $uid,
            'name' => input('title'),
            'type' => input('type'),
            'rows' => input('rows'),
            'question' => input('question'),
            'answer' => implode('|||', $param['answer']),

        );
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();

        } else {
            $apiService = new ApiService();
        }
        $result = $apiService->aiCreateTitle($data);
        if ($result['code'] == 1) {
            $log_no = getPayNo('Ait');
            user_balance_used($uid, $log_no, 2, 17, count($param['answer']));

        } else {

            return result(-1, '生成失败');
        }

        $create = new FigureAiTitle();
        foreach ($param['answer'] as $value) {
            $titleArray = explode('#', $value);
            $newText = str_replace("【", '', $titleArray[0]);

            $answer = str_replace("】", "", $newText);
            $answer = str_replace("标题：", "", $answer);
            unset($titleArray[0]);

            $titleCount = count($titleArray);
            unset($titleArray[$titleCount]);

            foreach ($titleArray as $key => $value) {

                if ($key > 4) {
                    unset($titleArray[$key]);
                }
            }

            $challenges = implode('#', $titleArray);

            $dataSave[] = array(
                'uid' => $uid,
                'type' => input('type'),
                'rows' => input('rows'),
                'question' => input('question'),
                'answer' => $answer,
                'title' => $param['title'],
                'create_time' => time(),
                'desc' => $param['desc'],
                'challenges' => $challenges


            );


        }


        $create->insertAll($dataSave);
        return result(0, '生成成功');


    }


    public function titleList()
    {
        try {
            $uid = input('uid');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }
            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));
            $where = " uid = {$uid} ";
            if (!empty(input('name'))) {
                $name = input('name');
                $where .= " AND name LIKE '%{$name}%'";
            }

            if (!empty(input('is_status'))) {
                $is_status = input('is_status');
                $where .= " AND is_status = '{$is_status}'";
            }
            $total = FigureAiTitle::where($where)->count();
            if ($total) {
                $list = FigureAiTitle::where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();

            } else {
                $list = array();
            }
            $totalPage = ceil($total / $psize);
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    public function delTitle()
    {
        try {
            $uid = input('uid');
            $create_id = input('create_id');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $create = FigureAiTitle::where([
                'uid' => $uid,
                'id' => $create_id
            ])->find();
            if (empty($create)) {
                return result(-1, '创作不存在');
            }

            $create->delete();
            return result(0, '删除成功');
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    public function titleInfo()
    {
        try {
            $uid = input('uid');
            $create_id = input('create_id');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $create = FigureAiTitle::where([
                'uid' => $uid,
                'id' => $create_id
            ])->find();
            if (empty($create)) {
                return result(-1, '创作不存在');
            }

            return result(0, 'success', $create);
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }

    }


    public function getVideoCopywriting()
    {

        $request = $this->request;
        $param = $request->param();
        $param['title'] = time();
        $uid = $param['uid'];
        $tally = sysconfig('tally', 'ai_video_extraction');
        $user = FigureUser::where('id', $uid)->find();

        if ($user['balance'] < $tally) {
            return result(-2, '余额不足，请充值');
        }

        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();

        } else {
            $apiService = new ApiService();

        }
        $result = $apiService->getVideoCopywriting($param);
        if (isset($result['code']) && $result['code'] == 1) {
            $dataSave = array(
                'uid' => $uid,
                'type' => input('type'),
                'rows' => 1,
                'question' => input('question'),
                'title' => $param['title'],
                'create_time' => time(),
                'jobId' => $result['data']
            );
            $create = new FigureAicreate();
            $create->save($dataSave);
            $log_no = getPayNo('AI');
            user_balance_used($uid, $log_no, 2, 12, 1);
            return result(0, '生成成功', $create);
        } else {
            return result(-1, $result['msg']);
        }
    }

    public function selectVideoCopywriting()
    {
        $request = $this->request;
        $param = $request->param();
        $create = new FigureAicreate();
        $info = $create->where(['id' => $param['id']])->find();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $result = $apiService->selectVideoCopywriting(['jobid' => $info['jobId']]);


        if ($result['code'] == 1) {
            if ($result['data']) {
                $audioFileName = basename($result['data']['voice']);
                $audioSrc = 'https://' . sysconfig('upload', 'alioss_domain') . '/' . $audioFileName;

                $ossClientUpload = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                    sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                    sysconfig('upload', 'alioss_endpoint')
                );
                if (!$ossClientUpload->doesObjectExist(sysconfig('upload', 'alioss_bucket'), $audioFileName)) {

                    $audioDownloadPath = root_path() . 'public/' . $audioFileName;
                    $ch = curl_init($result['data']['voice']);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                    $audioData = curl_exec($ch);
                    curl_close($ch);
                    // 将视频数据保存到本地文件
                    $audioFile = fopen($audioDownloadPath, 'wb');
                    fwrite($audioFile, $audioData);
                    fclose($audioFile);
                    $ossClient = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                        sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                        sysconfig('upload', 'alioss_endpoint')
                    );
                    $uploadAudioUrl = $ossClient->uploadFile(sysconfig('upload', 'alioss_bucket'), $audioFileName, $audioDownloadPath);
                    $audioSrc = $uploadAudioUrl['info']['url'];
                    // 上传阿里云后删除
                    unlink($audioDownloadPath);
                }
                try {
                    $config = new \Darabonba\OpenApi\Models\Config([
                        // 您的AccessKey ID
                        "accessKeyId" => sysconfig('upload', 'alioss_access_key_id'),
                        // 您的AccessKey Secret
                        "accessKeySecret" => sysconfig('upload', 'alioss_access_key_secret'),
                        'endpoint' => sysconfig('upload', 'alioss_clip_endpoint'),
                    ]);
                    $client = new ICE($config);
                    $ASRJob['inputFile'] = $audioSrc;

                    $submitASRJob = new SubmitASRJobRequest($ASRJob);
                    $runtime = new RuntimeOptions([]);
                    $submitASRJobsResult = $client->submitASRJobWithOptions($submitASRJob, $runtime);
                    $audio_jobid = $submitASRJobsResult->body->jobId;
                    $create->where(['id' => $param['id']])->update(['job_id' => $audio_jobid]);
                    return result(0, '生成成功', ['id' => $param['id']]);
                } catch (\Exception $exception) {
                    return result(-1, '失败');
                }
            } else {
                return result(-3, '未获取成功');
            }

        } else {
            return result(-1, $result['msg']);
        }

    }

    public function getCopywriting()
    {
        $request = $this->request;
        $param = $request->param();
        $create = new FigureAicreate();
        $info = $create->where(['id' => $param['id']])->find();

        $config = new \Darabonba\OpenApi\Models\Config([
            // 您的AccessKey ID
            "accessKeyId" => sysconfig('upload', 'alioss_access_key_id'),
            // 您的AccessKey Secret
            "accessKeySecret" => sysconfig('upload', 'alioss_access_key_secret'),
            'endpoint' => sysconfig('upload', 'alioss_clip_endpoint')//sysconfig('upload', 'alioss_clip_endpoint'),
        ]);
        $client = new ICE($config);
        $audioSmartHandleJobRequest = new GetSmartHandleJobRequest([
            "jobId" => $info['job_id']
        ]);
        $runtime = new RuntimeOptions([]);
        $audioSmartHandleJobResult = $client->getSmartHandleJobWithOptions($audioSmartHandleJobRequest, $runtime);

        if ($audioSmartHandleJobResult->body->state != 'Finished') {
            return result(-3, '未获取成功');
        }
        $textArray = json_decode($audioSmartHandleJobResult->body->jobResult->aiResult);
        $content = [];
        foreach ($textArray as $textValue) {
            $content[] = $textValue->content;
        }
        $content = implode(',', $content);
        $create->where(['id' => $param['id']])->update(['answer' => $content]);
        return result(1, '成功', ['content' => $content]);

    }

    public function doBaoVideoCopywriting()
    {
        $request = $this->request;
        $param = $request->param();
        $param['title'] = time();
        $uid = $param['uid'];
        $tally = sysconfig('tally', 'ai_video_extraction');
        $user = FigureUser::where('id', $uid)->find();
        if (!$user['is_member']) {
            if ($user['balance'] < $tally) {
                return result(-2, '余额不足，请充值');
            }
        } else {
            if ($user['ai_copywriting_times'] < 1 && $user['balance'] < $tally) {
                return result(-2, '余额不足，请充值');
            }
        }
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();

        } else {
            $apiService = new ApiService();

        }

        $result = $apiService->doBaoVideoCopywriting($param);
        if (isset($result['code']) && $result['code'] == 1) {
            $dataSave = array(
                'uid' => $uid,
                'type' => input('type'),
                'rows' => 1,
                'question' => input('question'),
                'title' => $param['title'],
                'create_time' => time(),
                'jobId' => $result['data']
            );
            $create = new FigureAicreate();
            $create->save($dataSave);
            $log_no = getPayNo('AI');
            user_balance_used($uid, $log_no, 2, 12, 1);
            return result(0, '生成成功', $create);
        } else {
            return result(-1, $result['msg']);
        }
    }

    public function testOne()
    {
        $domain = $_SERVER['SERVER_NAME'];


    }


    public function saveHomepage()
    {
        $request = $this->request;
        $param = $request->param();
        $homepageModel = new Homepage();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();

        }
        $uid = $param['uid'];
        $data['uid'] = $uid;
        $data['name'] = $param['name'];
        //   $data['video_count'] = $param['aweme_count'];
        $data['gather_count'] = $param['gather_count'];
        $data['share_text'] = $param['share_text'];
        $data['create_time'] = time();
        $user = FigureUser::where('id', $uid)->find();
        $tally = sysconfig('tally', 'douyin_homepage');
        if ($user['balance'] < $tally * $param['gather_count']) {
            return result(-2, '余额不足，请充值');
        }
        try {
            $homepageModel->startTrans();
            $homepageModel->insert($data);
            $home_id = $homepageModel->getLastInsID();
            $params = [
                'share_text' => $param['share_text'],
                'count' => $param['gather_count'],
                'max_cursor' => '',
            ];
            $result = $apiService->getComposition($params);
            $videoData = [];
            if (isset($result['code']) && $result['code'] == 1) {
                if ($result['data']) {
                    foreach ($result['data'] as $value) {

                        /*$videoFileName =time().uniqid().'.mp4';
                        $videoDownloadPath = root_path() . 'public/douyin' . $videoFileName;
                        $ch = curl_init($value['video_url']);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                        $videoDataUrl = curl_exec($ch);
                        curl_close($ch);
                        $videoFile = fopen($videoDownloadPath, 'wb');
                        fwrite($videoFile, $videoDataUrl);
                        fclose($videoFile);
                        $ossClient = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                            sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                            sysconfig('upload', 'alioss_endpoint')
                        );
                        $uploadVideoUrl = $ossClient->uploadFile(sysconfig('upload', 'alioss_bucket'), $videoFileName, $videoDownloadPath);
                        $ossFile = $uploadVideoUrl['info']['url'];
                         unlink($videoDownloadPath);*/
                        $videoData[] = [
                            'share_text' => $param['share_text'],
                            'count' => $param['gather_count'],
                            'video_url' => $value['video_url'],
                            'aweme_id' => $value['aweme_id'],
                            'uid' => $uid,
                            'home_id' => $home_id,
                            'create_time' => time(),
                            //   'oss_url' =>$ossFile

                        ];
                        $log_no = getPayNo('hd');
                        user_balance_used($uid, $log_no, 2, 32, 1);
                    }



                    $homepageVideoModel = new HomepageVideo();
                    $homepageVideoModel->insertAll($videoData);
                    $homepageModel->where(['id' => $home_id])->update(['count' => count($videoData)]);
                    $homepageModel->commit();
                }
            } else {
                $homepageModel->rollback();
                return result(-1, '失败', $result['msg']);
            }
        } catch (\Exception $exception) {
            $homepageModel->rollback();
            return result(-1, '失败', $exception->getMessage());
        }

        return result(0, '添加成功');
    }

    public function homepageList()
    {
        try {
            $uid = input('uid');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }
            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));
            $where['uid'] = $uid;
            if (!empty(input('name'))) {
                $name = input('name');
                $where['name'] = array('like', '%' . $name . '%');
            }

            $total = Homepage::where($where)->count();
            if ($total) {
                $list = Homepage::where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
                /*       foreach ($list as $key => $value) {

                           if ($total) {
                               $data = HomepageVideo::where($where)->order('create_time', 'desc')
                                   ->limit(($pindex - 1) * $psize, $psize)
                                   ->select();

                           } else {
                               $list = array();
                           }
                       }*/

            } else {
                $list = array();
            }
            $totalPage = ceil($total / $psize);
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    public function homevideoList()
    {
        try {
            $uid = input('uid');


            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }
            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));
            $where['uid'] = $uid;
            if (!empty(input('id'))) {
                $id = input('id');
                $where['home_id'] = $id;
            }

            $total = HomepageVideo::where($where)->count();
            if ($total) {
                $list = HomepageVideo::where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();

            } else {
                $list = array();
            }
            $totalPage = ceil($total / $psize);
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }


    public function HomepageCount()
    {
        $request = $this->request;
        $param = $request->param();
        $homepageModel = new Homepage();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $result = $apiService->HomepageCount($param);
        if ($result['code'] = 1) {
            if (isset($result['data'])) {
                return result(0, '获取成功', $result['data']);
            } else {
                return result(-1, '获取失败');
            }

        } else {
            return result(-1, '获取失败');
        }

    }

    public function homepageVideoRefresh()
    {
        $request = $this->request;
        $param = $request->param();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $homepageModel = new Homepage();
        $homeInfo = $homepageModel->where(['id' => $param['id']])->find();
        $tally = sysconfig('tally', 'douyin_homepage');
        $user = FigureUser::where('id', $homeInfo['uid'])->find();
        if ($user['balance'] < $tally * $homeInfo['gather_count']) {
            return result(-2, '余额不足，请充值');
        }
        $params = [
            'share_text' => $homeInfo['share_text'],
            'count' => $homeInfo['gather_count'],
            'max_cursor' => '',
        ];
        $result = $apiService->getComposition($params);
        if ($result['data']) {
            $homepageVideoModel = new HomepageVideo();
            $videoData = [];
            $count = 0;
            foreach ($result['data'] as $value) {
                $homepageVideoInfo = $homepageVideoModel->where(['aweme_id' => $value['aweme_id'], 'uid' => $homeInfo['uid']])->find();
                if (empty($homepageVideoInfo)) {
                  /*  $VideoPath = parse_url($value['video_url'], PHP_URL_PATH);
                    $videoFileName = basename($VideoPath);
                    $videoDownloadPath = root_path() . 'public/' . $videoFileName;
                    $ch = curl_init($value['video_url']);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                    $videoData = curl_exec($ch);
                    curl_close($ch);
                    // 将视频数据保存到本地文件
                    $videoFile = fopen($videoDownloadPath, 'wb');
                    fwrite($videoFile, $videoData);
                    fclose($videoFile);
                    $ossClient = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                        sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                        sysconfig('upload', 'alioss_endpoint')
                    );
                    $uploadVideoUrl = $ossClient->uploadFile(sysconfig('upload', 'alioss_bucket'), $videoFileName, $videoDownloadPath);
                    $ossFile = $uploadVideoUrl['info']['url'];
                    $count++;*/
                    $videoData[] = [
                        'share_text' => $homeInfo['share_text'],
                        'count' => $homeInfo['gather_count'],
                        'video_url' => $value['video_url'],
                        'aweme_id' => $value['aweme_id'],
                        'uid' => $homeInfo['uid'],
                        'home_id' => $homeInfo['id'],
                        'create_time' => time(),
                     //   'oss_url' =>$ossFile,

                    ];
                    $log_no = getPayNo('hd');
                    user_balance_used($homeInfo['uid'], $log_no, 2, 32, 1);
                }
            }
            if ($videoData) {
                $homepageModel->where(['id' => $param['id']])->inc('count', count($videoData))->update();
                $homepageVideoModel = new HomepageVideo();
                $homepageVideoModel->insertAll($videoData);
            }
        }
        return result(0, '本次刷新共获取' . $count . '条' . '扣除算力:' . $tally * $count);
    }

    public function videoAnalysis()
    {

        $request = $this->request;
        $param = $request->param();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $homepageModel = new HomepageVideo();
        $homeInfo = $homepageModel->where(['id' => $param['id']])->find();
        if ($homeInfo['status'] != 1){
            return result(-1, '数据暂未加载成功，请稍后重试');
        }

        $tally = sysconfig('tally', 'douyin_homepage_video');
        $user = FigureUser::where('id', $homeInfo['uid'])->find();
        if ($user['balance'] < $tally) {
            return result(-2, '余额不足，请充值');
        }
        $log_no = getPayNo('AI');
        $result = $apiService->videoAnalysis(['video_url' => $homeInfo['video_url']]);
        if ($result['code'] == 1) {
            if ($result['data']) {
                $homepageVideoModel = new HomepageVideo();
                $homepageVideoModel->where(['id' => $param['id']])->update(['job_id' => $result['data']['jobId']]);
                user_balance_used($homeInfo['uid'], $log_no, 2, 31, 1);
                return result(0, '刷新成功', ['job_id' => $result['data']['jobId'], 'id' => $param['id']]);
            } else {
                return result(-1, '请重新请求', ['job_id' => '', 'id' => $param['id']]);
            }
        } else {
            return result(-1, '失败', $result['msg']);
        }


    }

    public function homeVideoAudio()
    {
        $request = $this->request;
        $param = $request->param();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }

        $homepageModel = new HomepageVideo();
        $homeInfo = $homepageModel->where(['id' => $param['id']])->find();
        $result = $apiService->selectVideoCopywriting(['jobid' => $homeInfo['job_id']]);
        if ($result['code'] == 1) {

            if ($result['data']) {
                $audioFileName = basename($result['data']['voice']);
                $audioSrc = 'https://' . sysconfig('upload', 'alioss_domain') . '/' . $audioFileName;

                $ossClientUpload = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                    sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                    sysconfig('upload', 'alioss_endpoint')
                );
                if (!$ossClientUpload->doesObjectExist(sysconfig('upload', 'alioss_bucket'), $audioFileName)) {

                    $audioDownloadPath = root_path() . 'public/' . $audioFileName;
                    $ch = curl_init($result['data']['voice']);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                    $audioData = curl_exec($ch);
                    curl_close($ch);
                    // 将视频数据保存到本地文件
                    $audioFile = fopen($audioDownloadPath, 'wb');
                    fwrite($audioFile, $audioData);
                    fclose($audioFile);
                    $ossClient = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                        sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                        sysconfig('upload', 'alioss_endpoint')
                    );
                    $uploadAudioUrl = $ossClient->uploadFile(sysconfig('upload', 'alioss_bucket'), $audioFileName, $audioDownloadPath);
                    $audioSrc = $uploadAudioUrl['info']['url'];
                    // 上传阿里云后删除
                    unlink($audioDownloadPath);
                }
                try {
                    $config = new \Darabonba\OpenApi\Models\Config([
                        // 您的AccessKey ID
                        "accessKeyId" => sysconfig('upload', 'alioss_access_key_id'),
                        // 您的AccessKey Secret
                        "accessKeySecret" => sysconfig('upload', 'alioss_access_key_secret'),
                        'endpoint' => sysconfig('upload', 'alioss_clip_endpoint'),
                    ]);
                    $client = new ICE($config);
                    $ASRJob['inputFile'] = $audioSrc;

                    $submitASRJob = new SubmitASRJobRequest($ASRJob);
                    $runtime = new RuntimeOptions([]);
                    $submitASRJobsResult = $client->submitASRJobWithOptions($submitASRJob, $runtime);
                    $audio_jobid = $submitASRJobsResult->body->jobId;
                    $homepageModel->where(['id' => $param['id']])->update(['audio_job_id' => $audio_jobid]);
                    return result(0, '生成成功', ['id' => $param['id']]);
                } catch (\Exception $exception) {
                    return result(-1, '失败');
                }
            } else {
                return result(-3, '未获取成功');
            }
        } else {
            return result(-1, $result['msg']);
        }
        //   var_dump($result);
    }


    public function getHomeVideoAudioCopywriting()
    {
        $request = $this->request;
        $param = $request->param();
        $HomepageVideo = new HomepageVideo();
        $info = $HomepageVideo->where(['id' => $param['id']])->find();
        if (empty($info)) {
            return result(-1, '数据不存在');
        }
        if ($info['content']) {
            return result(0, '成功', ['content' => $info['content']]);
        }

        $config = new \Darabonba\OpenApi\Models\Config([
            // 您的AccessKey ID
            "accessKeyId" => sysconfig('upload', 'alioss_access_key_id'),
            // 您的AccessKey Secret
            "accessKeySecret" => sysconfig('upload', 'alioss_access_key_secret'),
            'endpoint' => sysconfig('upload', 'alioss_clip_endpoint')//sysconfig('upload', 'alioss_clip_endpoint'),
        ]);
        $client = new ICE($config);
        $audioSmartHandleJobRequest = new GetSmartHandleJobRequest([
            "jobId" => $info['audio_job_id']
        ]);
        $runtime = new RuntimeOptions([]);
        $audioSmartHandleJobResult = $client->getSmartHandleJobWithOptions($audioSmartHandleJobRequest, $runtime);


        if ($audioSmartHandleJobResult->body->state == 'Failed') {
            return result(-1, '失败');
        }
        if ($audioSmartHandleJobResult->body->state != 'Finished') {
            return result(-3, '未获取成功');
        }
        $textArray = json_decode($audioSmartHandleJobResult->body->jobResult->aiResult);
        $content = [];
        foreach ($textArray as $textValue) {
            $content[] = $textValue->content;
        }
        $content = implode(',', $content);
        $HomepageVideo->where(['id' => $param['id']])->update(['content' => $content]);
        return result(0, '成功', ['content' => $content]);

    }

    public function getHotspot()
    {

        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $result = $apiService->getHotspot();

        $redis = new \Redis();
        $password = isset(config('redis')["password"]) ? config('redis')["password"] : '';
        $port = empty(config('redis')["port"]) ? '6379' : config('redis')["port"];
        $redis->connect('127.0.0.1', $port);
        if (!empty($password)) {
            $redis->auth($password);
        }
        $top_three = $redis->get("top_three");
        $remaining = $redis->get("remaining");
        $returnData = [];
        if (empty($top_three) || empty($remaining)) {
            if ($result['code'] == 1) {
                if ($result['data']) {
                    $data = $result['data'];
                    $top_three = array_slice($data, 0, 3);
                    $redis->set("top_three", json_encode($top_three), 3600);
                    $redis->set("remaining", json_encode($data), 3600);
                    $keys = array_rand($data, 10);
                    $randomElements = array_intersect_key($data, array_flip($keys));
                    $returnData = array_merge($returnData, $top_three);
                    $returnData = array_merge($returnData, $randomElements);

                }
            }
        } else {
            $top_three = json_decode($top_three);
            $remaining = json_decode($remaining);
            $keys = array_rand($remaining, 10);
            $randomElements = array_intersect_key($remaining, array_flip($keys));
            $returnData = array_merge($returnData, $top_three);
            $returnData = array_merge($returnData, $randomElements);
        }
        return result(0, '刷新成功', $returnData);
    }

    public function localVideo()
    {

        $request = $this->request;
        $param = $request->param();
        $param['title'] = time();
        $uid = $param['uid'];
        $tally = sysconfig('tally', 'ai_video_extraction');
        $user = FigureUser::where('id', $uid)->find();

        if ($user['balance'] < $tally) {
            return result(-2, '余额不足，请充值');
        }

        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();

        } else {
            $apiService = new ApiService();

        }
        $result = $apiService->localVideo($param);
        if (isset($result['code']) && $result['code'] == 1) {
            $dataSave = array(
                'uid' => $uid,
                'type' => 20,
                'rows' => 1,
                'question' => input('question'),
                'title' => $param['title'],
                'create_time' => time(),
                'answer' => $result['data']['output'],
            );
            $create = new FigureAicreate();
            $create->save($dataSave);
            $log_no = getPayNo('AI');
            user_balance_used($uid, $log_no, 2, 12, 1);
            return result(0, '生成成功', $create);
        } else {
            return result(-1, $result['msg']);
        }
    }

    public function platformCopywriting()
    {

        $request = $this->request;
        $param = $request->param();
        $param['title'] = time();
        $uid = $param['uid'];
        $tally = sysconfig('tally', 'ai_video_extraction');
        $user = FigureUser::where('id', $uid)->find();

        if ($user['balance'] < $tally) {
            return result(-2, '余额不足，请充值');
        }

        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();

        } else {
            $apiService = new ApiService();

        }
        $result = $apiService->platformCopywriting($param);
        if (isset($result['code']) && $result['code'] == 1) {
            $dataSave = array(
                'uid' => $uid,
                'type' => 16,
                'rows' => 1,
                'question' => input('question'),
                'title' => $param['title'],
                'create_time' => time(),
                'answer' => $result['data']['output'],
            );
            $create = new FigureAicreate();
            $create->save($dataSave);
            $log_no = getPayNo('AI');
            user_balance_used($uid, $log_no, 2, 12, 1);
            return result(0, '生成成功', $create);
        } else {
            return result(-1, $result['msg']);
        }
    }

    public function createMediaJobs()
    {

        $request = $this->request;
        $param = $request->param();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }
        $homepageModel = new HomepageVideo();
        $homeInfo = $homepageModel->where(['id' => $param['id']])->find();
        if ($homeInfo['status'] != 1){
            return result(-1, '数据暂未加载成功，请稍后重试');
        }
        if ($homeInfo['content']){
            return result(0, '生成成功', ['id' => $param['id']]);
        }

        $tally = sysconfig('tally', 'douyin_homepage_video');
        $user = FigureUser::where('id', $homeInfo['uid'])->find();
        if ($user['balance'] < $tally) {
            return result(-2, '余额不足，请充值');
        }
        $log_no = getPayNo('AI');
        try {
            $result = $apiService->createMediaJobs();

            if ($result['code'] == 1){
                $config = new \Darabonba\OpenApi\Models\Config([
                    // 您的AccessKey ID
                    "accessKeyId" => sysconfig('upload', 'alioss_access_key_id'),
                    // 您的AccessKey Secret
                    "accessKeySecret" => sysconfig('upload', 'alioss_access_key_secret'),
                    'endpoint' => sysconfig('upload', 'alioss_clip_endpoint'),
                ]);
                $client = new ICE($config);
                $ASRJob['inputFile'] = $homeInfo['oss_url'];
                $submitASRJob = new SubmitASRJobRequest($ASRJob);
                $runtime = new RuntimeOptions([]);
                $submitASRJobsResult = $client->submitASRJobWithOptions($submitASRJob, $runtime);
                $audio_jobid = $submitASRJobsResult->body->jobId;
                $homepageModel->where(['id' => $param['id']])->update(['audio_job_id' => $audio_jobid]);
                user_balance_used($homeInfo['uid'], $log_no, 2, 31, 1);

            }else{
                return result(-1, $result['msg']);
            }

            return result(0, '生成成功', ['id' => $param['id']]);
        } catch (\Exception $exception) {
            return result(-1, '失败');
        }
       /* $result =   $result = $apiService->createMediaJobs(['outUrl' => $homeInfo['oss_url']]);
        //$apiService->createMediaJobs(['outUrl' => $homeInfo['oss_url']]);
        if ($result['code'] == 1) {
            if ($result['data']) {
                $homepageVideoModel = new HomepageVideo();
               $homepageVideoModel->where(['id' => $param['id']])->update(['job_id' =>  $result['data']]);
                user_balance_used($homeInfo['uid'], $log_no, 2, 31, 1);
                return result(0, '刷新成功',['job_id' => $result['data'],'id' => $param['id']]);
            } else {
                return result(-1, '请重新请求', ['job_id' => '', 'id' => $param['id']]);
            }
        } else {
            return result(-1, '失败', $result['msg']);
        }*/


    }


    public function describeMediaJob()
    {
        $request = $this->request;
        $param = $request->param();
        $homepageModel = new HomepageVideo();
        $info = $homepageModel->where(['id' => $param['id']])->find();
        if (sysconfig('account', 'operation_version') == 2) {
            $apiService = new AgentApiService();
        } else {
            $apiService = new ApiService();
        }

        $result = $apiService->describeMediaJob(['jobid' => $info['job_id']]);


        if ($result['code'] == 1) {
            $audioFileName = basename($result['data']['audio']);
           // $audioSrc = 'https://' . sysconfig('upload', 'alioss_domain') . '/' . $audioFileName;

            $ossClientUpload = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                sysconfig('upload', 'alioss_endpoint')
            );
//            if (!$ossClientUpload->doesObjectExist(sysconfig('upload', 'alioss_bucket'), $audioFileName)) {

                $audioDownloadPath = root_path() . 'public/' . $audioFileName;
                $ch = curl_init($result['data']['audio']);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                $audioData = curl_exec($ch);
                curl_close($ch);
                // 将视频数据保存到本地文件
                $audioFile = fopen($audioDownloadPath, 'wb');
                fwrite($audioFile, $audioData);
                fclose($audioFile);
                $ossClient = new OssClient(sysconfig('upload', 'alioss_access_key_id'),
                    sysconfig('upload', 'alioss_access_key_secret'),//'oss-cn-hangzhou.aliyuncs.com'
                    sysconfig('upload', 'alioss_endpoint')
                );
                $uploadAudioUrl = $ossClient->uploadFile(sysconfig('upload', 'alioss_bucket'), $audioFileName, $audioDownloadPath);
                $audioSrc = $uploadAudioUrl['info']['url'];
                // 上传阿里云后删除
                unlink($audioDownloadPath);
//            }
            try {
                $config = new \Darabonba\OpenApi\Models\Config([
                    // 您的AccessKey ID
                    "accessKeyId" => sysconfig('upload', 'alioss_access_key_id'),
                    // 您的AccessKey Secret
                    "accessKeySecret" => sysconfig('upload', 'alioss_access_key_secret'),
                    'endpoint' => sysconfig('upload', 'alioss_clip_endpoint'),
                ]);

                $client = new ICE($config);
                $ASRJob['inputFile'] = $audioSrc;



                $submitASRJob = new SubmitASRJobRequest($ASRJob);
                $runtime = new RuntimeOptions([]);
                $submitASRJobsResult = $client->submitASRJobWithOptions($submitASRJob, $runtime);

                $audio_jobid = $submitASRJobsResult->body->jobId;
                $homepageModel->where(['id' => $param['id']])->update(['audio_job_id' => $audio_jobid]);
                return result(0, '生成成功', ['id' => $param['id']]);
            } catch (\Exception $exception) {
                return result(-1, '失败');
            }
        } else if ($result['code'] == 0){
            return result(-1, $result['msg']);
        }else{

            return result(-3, $result['msg']);
        }

    }


}